package com.zhida.jiyangcenter.order

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.utils.*
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.flyco.animation.BounceEnter.BounceTopEnter
import com.flyco.animation.SlideExit.SlideBottomExit
import com.flyco.dialog.listener.OnBtnClickL
import com.flyco.dialog.widget.NormalDialog
import com.google.gson.Gson
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.*
import com.zhida.jiyangcenter.dialog.ExpressDialog
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.utils.glideImage
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.activity_order_shop.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@TitleBar(false)
@ContentLayout(R.layout.activity_order_shop)
class ShopOrderActivity : BaseActivity() {
    val adapter = Adapter()
    override fun initConfig(savedInstanceState: Bundle?) {
        title_bar.title("订单详情").color(resColor(R.color.white))
            .navigationIcon(R.drawable.iv_back_fill) {
                finish()
            }
        getData()
        rv_order.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_order.adapter = adapter
    }

    private fun getData() {
        lifecycleScope.request({
            APIAccount.service().productOrderInfo(intent.getStringExtra("uuid") ?: "")
        }, object : BaseAPI<ProductOrderInfoEntity>() {
            override fun onSuccess(t: ProductOrderInfoEntity?, state: Int, msg: String) {
                tv_order_num.text = "订单编号：" + t?.order?.order_code
                if (t?.order?.logistics_code.isNullOrEmpty()) {
                    ll_order_express.gone()
                } else {
                    ll_order_express.visible()
                    getExpress(t?.order?.logistics_yard ?: "", t?.order?.logistics_code ?: "")
                    ll_order_express.setOnClickListener {
                        if (expressEntity.Traces.isNullOrEmpty()) {
                            toast("暂无快递信息")
                        } else {
                            val dialog = ExpressDialog()
                            dialog.arguments = Bundle().apply {
                                putString("img", t?.order?.product?.get(0)?.picture)
                                putString("name", t?.order?.product?.get(0)?.name)
                                putString("num", t?.order?.logistics_code)
                            }
                            dialog.setExpressEntity(expressEntity.Traces!!)
                            dialog.show(supportFragmentManager, "ExpressDialog")
                        }
                    }
                }
                tv_order_address.text =
                    t?.order?.address?.name + "   " + t?.order?.address?.phone + "\n" + t?.order?.address?.detail_address
                tv_shop_order_money.text =
                    "共${t?.order?.product?.size}件商品 合计：¥${t?.order?.actual_payment}"
                tv_shop_order_zongjia.text = "￥${t?.order?.total_money}"
                tv_shop_order_yunfei.text = "￥${t?.order?.up_money}"
//                tv_shop_order_coupon.text="￥${t?.order?.up_money}"
                tv_shop_order_pay.text = "￥${t?.order?.actual_payment}"
                adapter.setNewData(t?.order?.product)
                when (t?.order?.state) {
                    "0" -> {
                        tv_order_type1.text = "待支付"
                        btn_operate.text = "去支付"
                        btn_operate.visible()
                        btn_operate.setOnClickListener {
                            startActivity<PayOrderActivity> {
                                putExtra("orderCode", t.order.order_uuid)
                                putExtra("total_money", t.order.actual_payment)
                                putExtra("kind", "0")
                            }
                        }
                    }
                    "1" -> {
                        tv_order_type1.text = "待发货"
                        btn_operate.text = " 退 款 "
                        btn_operate.visible()
                        btn_operate.setOnClickListener {
                            val dialog = NormalDialog(context)
                            dialog.content("您的商品还未发货，是否确认退款？")
                                .style(NormalDialog.STYLE_TWO)//
                                .title("退款")
                                .btnNum(2)
                                .btnTextColor(
                                    resColor(R.color.colorAccent),
                                    resColor(R.color.colorAccent)
                                )
                                .btnText("取消", "确认")
                                .titleTextSize(23f)
                                .showAnim(BounceTopEnter())
                                .dismissAnim(SlideBottomExit())
                                .show()

                            dialog.setOnBtnClickL(OnBtnClickL {
                                dialog.dismiss()
                            }, OnBtnClickL {
                                dialog.dismiss()
                                refundOrder(t.order.order_uuid ?: "")
                            })
                        }
                    }
                    "2" -> {
                        tv_order_type1.text = "待收货"
                        btn_operate.text = "确认收货"
                        btn_operate.visible()
                        btn_operate.setOnClickListener {
                            val dialog = NormalDialog(context)
                            dialog.content("请确保您已收到货物，是否确认收货？")
                                .style(NormalDialog.STYLE_TWO)//
                                .title("收货")
                                .btnNum(2)
                                .btnTextColor(
                                    resColor(R.color.colorAccent),
                                    resColor(R.color.colorAccent)
                                )
                                .btnText("取消", "确认")
                                .titleTextSize(23f)
                                .showAnim(BounceTopEnter())
                                .dismissAnim(SlideBottomExit())
                                .show()

                            dialog.setOnBtnClickL(OnBtnClickL {
                                dialog.dismiss()
                            }, OnBtnClickL {
                                dialog.dismiss()
                                receivingOrder(t.order.order_uuid ?: "")
                            })
                        }
                    }
                    "3" -> {
                        tv_order_type1.text = "待评价"
                        btn_operate.text = "去评价"
                        btn_operate.visible()
                        btn_operate.setOnClickListener {

                        }
                    }
                    "4" -> {
                        tv_order_type1.text = "已完成"
                        btn_operate.gone()
                    }
                    "5" -> {
                        tv_order_type1.text = "待退款"
                        btn_operate.gone()
                    }
                    "6" -> {
                        tv_order_type1.text = "已退款"
                        btn_operate.gone()

                    }
                    "7" -> {
                        tv_order_type1.text = "待退货"
                        btn_operate.gone()

                    }
                    "8" -> {
                        tv_order_type1.text = "已退货"
                        btn_operate.gone()
                    }
                    "9" -> {
                        tv_order_type1.text = "已取消"
                        btn_operate.gone()
                    }
                }
            }

            override fun onError(e: APIException) {
                tipFail(e.eMessage)
            }

        })
    }

    private fun receivingOrder(orderUuid: String) {
        lifecycleScope.request({ APIAccount.service().productOrderReceiving(orderUuid) },
            object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                    getData()
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }
            })
    }

    private fun refundOrder(orderUuid: String) {
        lifecycleScope.request({ APIAccount.service().productOrderRefund(orderUuid) },
            object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                    getData()
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }
            })
    }

    lateinit var expressEntity: ExpressEntity

    @SuppressLint("SetTextI18n")
    private fun getExpress(logistics_yard: String, logistics_code: String) {
        lifecycleScope.launch(Dispatchers.IO) {
            val result = KdniaoTrackQueryAPI().getOrderTracesByJson(
                logistics_yard,
                logistics_code
            )
            expressEntity = Gson().fromJson(
                result, ExpressEntity::class.java
            )
            withMain {
                if (!expressEntity.Traces.isNullOrEmpty())
                    tv_order_express.text =
                        (expressEntity.Traces?.get(expressEntity.Traces!!.size - 1)?.AcceptStation) + "\n" + (expressEntity.Traces?.get(
                            expressEntity.Traces!!.size - 1
                        )?.AcceptTime)
            }

        }
    }

    class Adapter :
        BaseQuickAdapter<ProductOrderInfoEntity.Order.Product, BaseViewHolder>(R.layout.item_item_shop_order) {
        override fun convert(helper: BaseViewHolder, item: ProductOrderInfoEntity.Order.Product?) {
            glideImage(helper.getView(R.id.niv_item_buy_car), item?.picture ?: "")
            helper.setText(R.id.tv_item_buy_car_name, item?.name)
                .setText(R.id.tv_item_buy_car_money, "￥${item?.price}")
                .setText(R.id.tv_item_num, "x${item?.num}")
        }

    }
}